package com.gm.commonlib.network.basenetwork.numberformat;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.youth.banner.util.LogUtils;

import java.io.IOException;

public class BooleanDefault0Adapter extends TypeAdapter<Boolean> {
    @Override
    public void write(JsonWriter out, Boolean value) throws IOException {
        if (value == null) {
            out.nullValue();
        } else {
            out.value(value);
        }
    }
    @Override
    public Boolean read(JsonReader in) throws IOException {
        final JsonToken peekValue = in.peek();
        if (peekValue == JsonToken.NULL) {
            in.nextNull();
            return false;
        }

        if (peekValue == JsonToken.BOOLEAN) {
            return in.nextBoolean();
        }

        try {
            String result = in.nextString();
            if (result == null || result.equals("") || result.equals("null") || result.equals("{}")) {
                return false;
            }

            if (result.equalsIgnoreCase("true")) {
                return true;
            }
            if (result.equalsIgnoreCase("false")) {
                return false;
            }
            if (result.matches("\\d+|\\d+[.]\\d+|\\d+[.]|[.]\\d+")) {
                double number = Double.parseDouble(result);
                if (number > 0) {
                    //TODO 非0 为true
                    return true;
                }
            }
        } catch (Exception e) {
            LogUtils.d(e.toString());
        }

        return false;
    }
}
